import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fly_car/search_bar_delegate.dart';

import 'baidu_map_page.dart';

var httpClient = new HttpClient();

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  Map location;

  //目的地
  Map target;

  TextEditingController textEditingController = TextEditingController();
  //地图组件的id
  GlobalKey<BaiduMapPageState> baiduMapKey = GlobalKey();

  //获取百度地图 定位后的数据
  getBaiDuMapLocation(Map location) {
    this.location = new Map<String, dynamic>.from(location);
    setState(() {});
  }


  //获取路径规划
  get() async {
    var lantitude = location['latitude'];
    var longitude = location['longitude'];
    var tLat = target['location']['lat'];
    var tLng = target['location']['lng'];

    Map<String, String> param = {
      'origin': "$lantitude,$longitude",
      'destination': "$tLat,$tLng",
      "output": "json",
      "ak": "WS9HXr6YEGmdLQWGFHvgrBy5ODT81x1l"
    };
    var uri = new Uri.http('api.map.baidu.com', '/direction/v2/riding', param);
    var request = await httpClient.getUrl(uri);
    var response = await request.close();
    if (response.statusCode == 200) {
      print('请求成功');
      var responseBody = await response.transform(utf8.decoder).join();
      Map data = jsonDecode(responseBody);
      var result = data['result'];
      print('responseBody = $responseBody');
    } else {
      print('请求失败');
    }
  }

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    textEditingController.addListener(() {
      get();

    });
  }

  @override
  Widget build(BuildContext context) {
    //定位显示的地点
    var locationDetail = location != null ? location['locationDetail'] : '正在定位';
    //百度组件的key
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        leading: Icon(
          Icons.account_circle,
          color: Colors.black,
        ),
        actions: [
          IconButton(
            padding: EdgeInsets.all(1.0),
            onPressed: () => {
              //路由跳转
              // Navigator.pushNamed(context, '/message')
            },
            icon: Icon(
              Icons.message,
              color: Colors.black,
            ),
          ),
          IconButton(
            padding: EdgeInsets.all(1.0),
            onPressed: () => {},
            icon: Icon(
              Icons.qr_code,
              color: Colors.black,
            ),
          ),
        ],
        title: Row(
          children: [
            Icon(Icons.home),
            DropdownButton(
                value: "km",
                items: [DropdownMenuItem(child: Text("昆明市"), value: "km")],
                onChanged: (v) => {})
          ],
        ),
      ),
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          BaiduMapPage(
            getBaiDuMapLocation,
            key: baiduMapKey,
          ),
          Positioned(
              right: 20,
              bottom: 200,
              //圆角
              child: GestureDetector(
                onTap: () {
                  //点击定位按钮  调用地图组件的定位方法 去定位
                  baiduMapKey.currentState.startLocation();
                  //更新用户定位的位置
                  baiduMapKey.currentState.updateLocation();
                },
                child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        color: Colors.white,
                        borderRadius: BorderRadius.circular((10.0))),
                    width: 40,
                    height: 40,
                    child: Icon(Icons.gps_fixed)),
              )),
          Positioned(
            left: 20,
            right: 20,
            height: 170,
            bottom: 20,
            child: Card(
                elevation: 20,
                shadowColor: Colors.grey,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Container(
                            width: 10,
                            height: 10,
                            decoration: BoxDecoration(
                              color: Colors.red,
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                        Expanded(
                          child: ListTile(
                            title: Text(
                              locationDetail,
                              style:
                                  TextStyle(color: Colors.black, fontSize: 16),
                            ),
                            subtitle: Text(
                              "为您推荐附件的最佳上车地点",
                              style: TextStyle(
                                  color: Colors.blueAccent, fontSize: 12),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Divider(),
                    Row(
                      children: [
                        Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Container(
                            width: 10,
                            height: 10,
                            decoration: BoxDecoration(
                              color: Colors.blue,
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                        Expanded(
                          child: ListTile(
                              onTap: () {
                                //进入 选择地址的页面 并发选择地址页面的地理信息带回来
                                Future future = Navigator.pushNamed(
                                    context, '/search',
                                    arguments: location);
                                future.then((value) {
                                  target = Map.from(value);
                                  textEditingController.text =
                                      target != null ? target['name'] : '';
                                });
                              },
                              subtitle: Text(
                                "您要去哪儿",
                                style: TextStyle(
                                    color: Colors.blueAccent, fontSize: 12),
                              ),
                              title: TextField(
                                readOnly: true,
                                controller: textEditingController,
                                decoration: InputDecoration.collapsed(),
                                onChanged: (v) {
                                  //值改变  路径规划
                                  get();
                                },
                              )

                              // Text(
                              //   target != null ? target['name'] : '',
                              //   style:
                              //       TextStyle(color: Colors.grey, fontSize: 18),
                              // ),
                              ),
                        ),
                      ],
                    ),
                  ],
                )),
          )
        ],
      ),
    );
  }
}
